"use client";

import { useEffect, useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import { Spin } from "antd";

// 不需要认证的路径
const publicPaths = ["/login", "/register"];

export default function withAuth<P extends object>(
  Component: React.ComponentType<P>
) {
  return function WithAuth(props: P) {
    const router = useRouter();
    const pathname = usePathname();
    const [isLoading, setIsLoading] = useState(true);
    const [isAuthenticated, setIsAuthenticated] = useState(false);

    useEffect(() => {
      // 检查是否有token (从cookie或者localstorage中获取)
      const getCookie = (name: string) => {
        const value = `; ${document.cookie}`;

        const parts = value.split(`; ${name}=`);
        if (parts.length === 2) return parts.pop()?.split(";").shift();
        return undefined;
      };

      const token = getCookie("token");
      const isAuth = !!token;
      setIsAuthenticated(isAuth);

      const isPublicPath = publicPaths.includes(pathname);

      // 如果是公开路径且已认证，重定向到首页
      if (isPublicPath && isAuth) {
        router.push("/");
      }
      // 如果是受保护路径且未认证，重定向到登录页
      else if (!isPublicPath && !isAuth) {
        router.push("/login");
      }

      setIsLoading(false);
    }, [pathname, router]);

    if (isLoading) {
      return (
        <div
          style={{
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            height: "100vh",
          }}
        >
          <Spin size="large" tip="验证登录状态..." />
        </div>
      );
    }
    const isPublicPath = publicPaths.includes(pathname);
    if (
      (isPublicPath && !isAuthenticated) ||
      (!isPublicPath && isAuthenticated)
    ) {
      return <Component {...props} />;
    }
    return (
      <div
        style={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          height: "100vh",
        }}
      >
        <Spin size="large" tip="跳转中..." />
      </div>
    );
  };
}
